import { Provide } from "@midwayjs/decorator";
import { InjectEntityModel } from "@midwayjs/typegoose";
import { ReturnModelType } from "@typegoose/typegoose";
import { AccessLog } from "../entity/accesslog";
import { RespInfo } from "../types/common.type";
import { RespMethod } from "../util/common.method";

@Provide()
export class AccessLogService {



  @InjectEntityModel(AccessLog)
  accessLogModel: ReturnModelType<typeof AccessLog>;

  /** 生成一条访问日志 */
  async addlog(path: string, ip: string, ua: string, user?: string): Promise<void> {
    await this.accessLogModel.create({ path, ip, ua, user })
  }

  /** 获取访问日志列表 */
  async list(page: number = 0, number: number = 0): Promise<RespInfo> {
    const list = await this.accessLogModel.find({}).skip((page - 1) * number).limit(number).sort([['created', -1]])
    const total = (await this.accessLogModel.find({})).length;
    return RespMethod({ list, total, page: Math.ceil(total / number) })
  }


}